/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package x10.interfaces.cm15a.receive;

import x10.utilities.ChunkOfBytes;
import java.util.BitSet;
import x10.enums.Interfaces;
import x10.event.X10Command;
import x10.event.X10Event;
import x10.utilities.BitSetUtils;

/**
 *
 * @author Denny
 */
public class RFMessageFactory extends X10DeviceReceiver {
    byte[] message;
    X10Command lastX10Command = null;
    X10Event lastX10SecurityDevice = null;
    public static final byte rfX10Remote = (byte)0x14;              //TV Remote or Camera Remote
    public static final byte rfX10Command = (byte)0x20;             //RF version of the Powerline Command
    public static final byte rfX10SecurityDevice = (byte)0x29;      //DS10A, MS10A, KR10A
    private byte rfMessageHeader = (byte)0x00;
    int commandIdentifierByte = 4;
    int securityCommandBit = 6;

    public RFMessageFactory(LastAddressedTracker lat, Interfaces interfaceType){
        super(lat, interfaceType);
    }

    public X10Event process(ChunkOfBytes bytes){
        X10Event device;
        this.message = bytes.getBytes();
        rfMessageHeader = message[1]; //Message Header - Byte 2

        if(isCommand()){

            if(isSecurityCommand()){

                RFSecurityCommandMessage rf_secMessage = new RFSecurityCommandMessage(bytes);
                device = rf_secMessage.parse();

            } else {

                RFPowerLineMessage rf_plMessage = new RFPowerLineMessage(bytes, lat);
                device = rf_plMessage.parse();

            }
        } else if (isSecurityDevice()){

            RFSecurityDeviceMessage ds10aMessage = new RFSecurityDeviceMessage(bytes);
            device = ds10aMessage.parse();

        } else if (isRemote()){

            RFRemoteMessage remoteMessage = new RFRemoteMessage(bytes);
            device = remoteMessage.parse();

        } else {

            device = null;
            System.out.println("RF UNK: " + bytes.toString());

        }

        return device;
    }

    private boolean isCommand(){
        if(rfMessageHeader == rfX10Command){
            return true;
        } else {
            return false;
        }
    }

    private boolean isRemote(){
        if(rfMessageHeader == rfX10Remote){
            return true;
        } else {
            return false;
        }
    }

    private boolean isSecurityDevice(){
        if(rfMessageHeader == rfX10SecurityDevice){
            return true;
        } else {
            return false;
        }
    }

    private boolean isSecurityCommand(){
        BitSet bits = BitSetUtils.byteToBitSet(message[commandIdentifierByte]);
        if(bits.get(securityCommandBit)){
            return true;
        } else {
            return false;
        }
    }
}
